home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c,comp.unix.programmer
- Path: news.uunet.ca!wildcan!sq!msb
- From: msb@sq.com (Mark Brader)
- Subject: Re: Q: '\n' character
- Message-ID: <1996Apr14.015303.23020@sq.com>
- Organization: SoftQuad Inc., Toronto, Canada
- References: <4kj66f$k0o@ren.cei.net> <1996Apr11.192937.25676@sq.com> <829396473snz@genesis.demon.co.uk>
- Date: Sun, 14 Apr 1996 01:53:03 GMT
-
- > > Instead use:
- > >
- > > len = strlen (buffer);
- > > if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = '\0';
- > >
- > > Both tests in the "if" are necessary.
- >
- > Not exactly true. fgets() can never place a zero length string in the
- > buffer.
-
- It can if there's a null character at the start of the line in the
- input. (One thing you give up by using fgets() is the ability to
- do anything with useful text that follows a null character on the input
- line, but at least you should avoid making out-of-bounds array references
- if there is one.)
-
- Demonstration:
-
- #include <stdio.h>
- #include <assert.h>
-
- main()
- {
- FILE *fin, *fout;
- char buf[64];
-
- fout = fopen ("temp", "w");
- assert (fout != NULL);
-
- putc ('\0', fout);
- fprintf (fout, "Hello world\n");
- fclose (fout);
-
- fin = fopen ("temp", "r");
- assert (fin != NULL);
- assert (fgets (buf, sizeof buf, fin) == buf);
-
- printf ("length %d, first byte %d\n", strlen (buf), buf[0]);
- printf ("buf as string ``%s'', buf+1 as string ``%s''\n",
- buf, buf+1);
-
- fclose (fin);
- remove ("temp");
- return 0;
- }
-
- On this system, the output is:
-
- length 0, first byte 0
- buf as string ``'', buf+1 as string ``Hello world
- ''
-
- --
- Mark Brader "Sir, your composure baffles me. A single counter-
- msb@sq.com example refutes a conjecture as effectively as ten.
- SoftQuad Inc. ... Hands up! You have to surrender."
- Toronto -- Imre Lakatos
-
- My text in this article is in the public domain.
-